import React, { Component } from 'react';
import { Input, Modal, Form, Icon, message } from 'antd';
import PropTypes from 'prop-types';
import { changePassword } from '@api/user';
import { PASSWORD_STRICT_RE } from '@util/constants';
import { connect } from 'react-redux';
import validatorCreator from '@util/validator-creator';
import rsa from '@util/rsa';
import _ from 'lodash';
import './index.less';

const FormItem = Form.Item;
const prefixCls = 'password-modal';

const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
};

class PasswordModal extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  UNSAFE_componentWillReceiveProps(props) {
    const {
      visible = false,
      form: { resetFields }
    } = props;
    if (visible === false) {
      resetFields();
    }
  }

  compareToFirstPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('newPassword')) {
      callback('前后密码输入必须一致！');
    } else {
      callback();
    }
  };

  onClickSubmit = () => {
    const {
      form: { validateFieldsAndScroll }
    } = this.props;
    validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      if (values.oldPassword === values.newPassword) {
        message.error('新密码不能与旧密码相同');
        return false;
      }
      const publicKey = this.props.publicKey;
      const formatedData = {
        oldPassword: rsa.encrypt(values.oldPassword, publicKey),
        newPassword: rsa.encrypt(values.newPassword, publicKey)
      };
      this.setState({ loading: true });
      changePassword(formatedData)
        .then(() => {
          message.success('修改密码成功');
          this.setState({ loading: false }, this.props.changePasswordModalVisible());
        })
        .catch(() => {
          message.error('密码输入错误，修改失败');
          this.setState({ loading: false });
          this.props.form.setFieldsValue({
            oldPassword: '',
            newPassword: '',
            confirmNewPassword: ''
          });
        });
    });
  };

  render() {
    const { visible = false } = this.props;
    const {
      form: { getFieldDecorator }
    } = this.props;

    return (
      <div className="password-modal">
        <Modal
          maskClosable={false}
          title={<span style={{ fontWeight: 600 }}>修改密码</span>}
          className={`${prefixCls}-modal`}
          visible={visible}
          width={520}
          onCancel={() => this.props.changePasswordModalVisible()}
          onOk={this.onClickSubmit}
        >
          <Form>
            <FormItem {...formItemLayout} key="oldPassword" label="原 密 码" colon={false}>
              {getFieldDecorator('oldPassword', {
                validate: [
                  {
                    rules: [
                      {
                        required: true,
                        message: '此项不能为空'
                      }
                    ]
                  }
                ]
              })(<Input type="password" placeholder="请输入" />)}
            </FormItem>
            <FormItem {...formItemLayout} key="newPassword" label="新 密 码" colon={false}>
              {getFieldDecorator('newPassword', {
                validate: [
                  {
                    rules: [
                      {
                        validator: validatorCreator('密码', {
                          reg: PASSWORD_STRICT_RE,
                          required: true,
                          min: 8,
                          max: 16
                        })
                      }
                    ]
                  }
                ]
              })(
                <Input
                  type="password"
                  placeholder="密码长度8到16位，必须包含数字、字母和特殊字符"
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} key="porifmPassword" label="确认密码" colon={false}>
              {getFieldDecorator('confirmNewPassword', {
                validate: [
                  {
                    rules: [
                      { required: true, message: '此项不能为空' },
                      {
                        validator: this.compareToFirstPassword
                      }
                    ]
                  }
                ]
              })(<Input type="password" placeholder="请再次输入新密码" />)}
            </FormItem>
          </Form>
          <span className={`${prefixCls}-message`} style={{ marginLeft: 80, color: '#999ea8' }}>
            <Icon type="exclamation-circle" />
            忘记密码，请联系超级管理员
          </span>
        </Modal>
      </div>
    );
  }
}

PasswordModal.propTypes = {
  form: PropTypes.object.isRequired,
  changePasswordModalVisible: PropTypes.function,
  visible: PropTypes.boolean,
  publicKey: PropTypes.string
};

const mapStateToProps = state => {
  return {
    publicKey: _.get(state, 'auth.cert.publicKey', '')
  };
};

export default connect(mapStateToProps)(Form.create()(PasswordModal));
